package com.aruba.shaderapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 放大镜效果
 */
public class ZoomImageView extends View {
    private Paint paintS = new Paint();
    private Bitmap bitmapS;
    private Paint paintB = new Paint();
    private Bitmap bitmapB;
    private BitmapShader bitmapShader;
    private Matrix bitmapMatrix = new Matrix();

    private float currentX = -1, currentY = -1;
    private float dx, dy;
    //放大镜半径
    private int radius = 100;

    public ZoomImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        bitmapS = BitmapFactory.decodeResource(getResources(), R.mipmap.xyjy2);
        bitmapB = Bitmap.createScaledBitmap(bitmapS,bitmapS.getWidth()*3,bitmapS.getHeight()*3,true);

        bitmapShader = new BitmapShader(bitmapB, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        paintB.setShader(bitmapShader);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                currentX = event.getX();
                currentY = event.getY();

                postInvalidate();
                break;
            case MotionEvent.ACTION_UP:
                currentX = -1;
                currentY = -1;

                postInvalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                //计算偏移量,要使大图和小图的点一致
                dx =- event.getX()* bitmapB.getWidth() / bitmapS.getWidth() + radius;
                dy =- event.getY() * bitmapB.getHeight() / bitmapS.getHeight()+ radius;

                currentX = event.getX();
                currentY = event.getY();

                postInvalidate();
                break;
        }

        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //画原图
        canvas.drawBitmap(bitmapS, 0, 0, paintS);

        //画放大图片
        if (currentX != -1) {
            bitmapMatrix.setTranslate(dx , dy);
            bitmapShader.setLocalMatrix(bitmapMatrix);
            canvas.drawCircle(currentX - radius/2, currentY-radius/2, radius, paintB);
        }
    }
}
